/**
 * Copyright &copy; 2016-2017 <a href="http://git.oschina.net/whoamien/backend_management">Backend Management</a> All rights reserved.
 */
package com.xw.app.controller;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.xw.app.model.SysDict;
import com.xw.app.model.SysDict;
import com.xw.app.model.SysDict;
import com.xw.app.service.SysDictService;
import com.xw.app.vo.query.AcctRoleQuery;
import com.xw.app.vo.query.SysDictQuery;
import com.xw.framework.base.controller.BaseSpringController;
import com.xw.framework.vo.UserMenu;
import com.xw.util.BeanUtils;

/**
 * The Class SysDictController.
 *
 * @author Xi Wei
 */
@Controller
@RequestMapping("/sysDict")
public class SysDictController extends BaseSpringController {
	
	@Autowired
	private SysDictService sysDictService;
	
	/**
	 * List.
	 *
	 * @param request the request
	 * @param query the query
	 * @param redirectAttributes the redirect attributes
	 * @return the model and view
	 */
	@RequestMapping("/list")
	public ModelAndView list(HttpServletRequest request,SysDictQuery query,RedirectAttributes redirectAttributes){
		List<SysDict> parentList = Lists.newArrayList();
		if(query.getParentId() != null){
			SysDict parent = sysDictService.getById(query.getParentId());
			query.setDictLevel(parent.getDictLevel() + 1);
			parentList.add(parent);
			while(parent.isHasParent()){
				parent = sysDictService.getById(parent.getParent().getId());
				parentList.add(parent);
			}
			Collections.reverse(parentList);
			
		}
		
		Page<SysDict> page = sysDictService.findPage(query);
		request.getSession().setAttribute(AcctRoleQuery.class.getSimpleName(), query);
		ModelAndView result = new ModelAndView("/SysDict/list");
		
		ModelMap map = toModelMap(page, query);
		map.addAttribute("parentList", parentList);
		syncMessage(request,map);
		result.addAllObjects(map);
		return result;		
	}
	
	/**
	 * Creates the.
	 *
	 * @param sysDict the sys dict
	 * @param redirectAttributes the redirect attributes
	 * @return the model and view
	 */
	@RequestMapping("/popup/create")
	public ModelAndView create(SysDict sysDict,RedirectAttributes redirectAttributes){
		ModelAndView result = new ModelAndView("/SysDict/add");
		ModelMap map = new ModelMap();
		Long id = sysDict.getId();
		if(id != null){
			sysDict = sysDictService.getById(id);
		}
		if(sysDict == null && id != null){
			map.addAttribute("errorKey", "error.record.notfound");
			sysDict = new SysDict();
		}
		map.addAttribute("sysDict", sysDict);
		result.addAllObjects(map);
		return result;
	}
	
	
	/**
	 * Save.
	 *
	 * @param sysDict the sys dict
	 * @param validateResult the validate result
	 * @param request the request
	 * @param redirectAttributes the redirect attributes
	 * @return the model and view
	 */
	@RequestMapping("/popup/save")
	public ModelAndView save(@Valid SysDict sysDict,BindingResult validateResult,HttpServletRequest request,RedirectAttributes redirectAttributes){
		if(validateResult.hasErrors()){
			return create(sysDict,redirectAttributes);
		}
		int menuLevel = 1;
		if(sysDict.getParent() != null && sysDict.getParent().getId() != null){
			sysDict.setParent(sysDictService.getById(sysDict.getParent().getId()));
			sysDict.setParentCode(sysDict.getParent().getDictCode());
			menuLevel = sysDict.getParent().getDictLevel() + 1;
		}else{
			sysDict.setParent(null);
		}
		
		sysDict.setDictLevel(menuLevel);
		if(sysDict.getId() != null){
			SysDict existing = sysDictService.getById(sysDict.getId());
			sysDict.setSubDictList(existing.getSubDictList());
			BeanUtils.copyProperties(existing, sysDict);
			sysDictService.save(existing);
			addSuccessMessageInSession(request, false);
		}else{
			sysDictService.save(sysDict);
			addSuccessMessageInSession(request, true);
		}
		
		
		ModelMap map = new ModelMap();
		ModelAndView result = new ModelAndView("/saveResult");
		map.addAttribute("msg", "success");
		
		result.addAllObjects(map);
		return result;
	}
	
	/**
	 * Delete.
	 *
	 * @param id the id
	 * @return the string
	 */
	@RequestMapping("/json/delete")
	@ResponseBody
	public String delete(Long id){
		sysDictService.delete(id);
		return "success";
		
	}
	
	/**
	 * Delete all.
	 *
	 * @param ids the ids
	 * @return the string
	 */
	@RequestMapping("/json/deleteAll")
	@ResponseBody
	public String deleteAll(String ids){
		System.out.println(ids);
		if(ids != null && ids.trim().length() > 0){
			Arrays.asList(ids.split(",")).forEach(x -> sysDictService.delete(Long.valueOf(x)));
		}
		return "success";
	}
	
	/**
	 * Check code.
	 *
	 * @param dictCode the dict code
	 * @param id the id
	 * @param parentId the parent id
	 * @return the string
	 */
	@RequestMapping("/json/checkCode")
	@ResponseBody
	public String checkCode(String dictCode,Long id,Long parentId){
		if(sysDictService.checkCodeExist(dictCode,id,parentId)){
			return "false";
		}
		return "true";
	}
	
}
